#include "login.h"
#include "ui_login.h"
#include "register.h"
#include "gamehall.h"
#include<QDebug>
Login::Login(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Login)
{
    ui->setupUi(this);
    ui->lineEdit_password->setEchoMode(QLineEdit::Password);
    ui->lineEdit_username->setClearButtonEnabled(true);
    ui->lineEdit_password->setClearButtonEnabled(true);

    manager = new QNetworkAccessManager(this);
}

Login::~Login()
{
    delete ui;
}

void Login::on_pushButton_register_clicked()
{
    QDialog* reg = new Register(this);
    reg->exec();
}

void Login::on_checkBox_clicked(bool checked)
{
    static QString password = "";
    QString text = ui->lineEdit_password->text();
    if(checked && !text.isEmpty())
    {
        password = text;
    }
    else if (checked && text.isEmpty()) {
        ui->lineEdit_password->setText(password);
    }
}

void Login::on_checkBox_2_clicked(bool checked)
{
    if(checked)
    {
        ui->lineEdit_password->setEchoMode(QLineEdit::Normal);
    }
    else
    {
        ui->lineEdit_password->setEchoMode(QLineEdit::Password);
    }
}

void Login::on_pushButton_login_clicked()
{
    if(ui->lineEdit_username->text() == "")
    {
        qDebug() << "用户名为空";
        return;
    }
    if(ui->lineEdit_password->text() == "")
    {
        qDebug() << "密码为空";
        return;
    }

    //1.获取到输入框中的url
    QString name = "/login";
    QUrl url(URL + name);
    //2.构造一个HTTP请求对象
    QNetworkRequest request(url);
    //3.发送请求
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    //QNetworkReply* response = manager->get(request);
    //将请求进行反序列化
    QJsonObject req;//创建一个json对象
    req.insert("username", QJsonValue(ui->lineEdit_username->text()));
    req.insert("password", QJsonValue(ui->lineEdit_password->text()));
    response = manager->post(request, QJsonDocument(req).toJson());
    //4.通过信号槽，来处理函数
    connect(response, &QNetworkReply::finished, this, &Login::handle_resp);
}

void Login::handle_resp()
{
    if(response->error() == QNetworkReply::NoError)
    {
        //获取请求头
        QString ssid = response->rawHeader("Set-Cookie");
        qDebug() << "login_ssid:" << ssid;
        resp = response->readAll();
        //响应正确收取到了
        //QMessageBox::information(this, "服务端响应", resp, QMessageBox::Ok);

        qDebug() << "登陆成功";
        qDebug() << "进入游戏大厅";
        gameHall* gamehall = new gameHall;
        gamehall->get_info(ssid);//获取用户信息
        gamehall->ws_hall(ssid);//建立长连接
        gamehall->show();
        this->hide();
    }
    else
    {
        resp = response->readAll();
        qDebug() << "handle_login:" << resp;
        qDebug() << "登录失败";
        //响应出错了
        //QMessageBox::critical(this, "服务端响应", resp, QMessageBox::Ok);

    }
    //对response进行释放
    response->deleteLater();
}
